<?php

namespace App\Services;

use App\Models\ElectricPaymentOrder;
use App\Models\SysRegion;
use App\Models\Users;

class PropertyService
{
    /**
     * 获取
     * @param $user
     * @param $plan
     * @return array
     */
    public function getCostArr($user, $plan): array
    {
        [$payableOrder, $paid_order_total] = self::getPayableOrder($user['id']);
        [$cumulativeConsumptionOrders, $cumulativeConsumption] = self::getCumulativeConsumptionOrders($user['id']);
        [$one_price, $year_total, $last_month] = self::getNowBalance($user, $plan);
        [$need_arr, $arr1, $arrears, $unpaid_arr] = $this->getNeedArr($one_price, $plan, $user);
        return [
            'one_price' => $one_price,//单月物业费
            'year_total' => $year_total,//年度应缴纳物业费
            'last_month' => $last_month,//缴纳截至月份
            'cumulativeConsumption' => $cumulativeConsumption,//累计消费金额
            'payableOrder' => $payableOrder,//已缴费订单
            'cumulativeConsumptionOrders' => $cumulativeConsumptionOrders,//累计消费订单
            'billed_arr' => $need_arr,//缴费订单详细
            'arr1' => $arr1,//已缴纳月份
            'arrears' => $arrears,//已出帐
            "unpaid_arr" => $unpaid_arr//未出帐
        ];
    }

    /**
     * 获得·地址数组
     * @param $one_user
     * @return array
     * @author Sdd
     */
    public static function getAddressArr($one_user)
    {
        extract($one_user, null);
        /**
         * @var $province |省份
         * @var $city |市
         * @var $area |区县
         * @var $community |小区
         * @var $community_area |小区分区
         * @var $room_number |房间号
         */
        $arr = SysRegion::whereIn("id", [$province, $city, $area])->pluck("name")->toArray();
        $address = implode('>', $arr);
        return [
            'address' => $address,
            'community_name' => $community,//小区名称
            'community_area_name' => $community_area,//小区分区
            'room_number' => $room_number,//房间号
        ];
    }

    /**
     * 获取缴费订单详情数组
     * @param $one_price
     * @param $plan
     * @param $user
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author Sdd
     */
    public function getNeedArr($one_price, $plan, $user): array
    {
        [$arrears, $cha, $billed_arr, $paid_month, $unpaid_arr] = $this->get_property_need($user, $plan, $one_price);


        return [$billed_arr, $paid_month, $arrears, $unpaid_arr];
    }

    /**
     * 已缴纳费用
     * @param $id
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author Sdd
     */
    public static function getPayableOrder($id)
    {
//已缴纳费用
        $str = 'id,paymentMoney,pay_type,feeType';
        $arr = ['feeType' => 3, 'user_id' => $id, 'status' => 2];
        $payableOrder = ElectricPaymentOrder::getOrdersByWhere($str, $arr, 1);
        $paid_order_total = array_sum(array_column($payableOrder, 'paymentMoney'));
        return array($payableOrder, $paid_order_total);//已缴纳费用
    }

    /**
     * 累计缴纳订单
     * @param $id
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author Sdd
     */
    public static function getCumulativeConsumptionOrders($id)
    {
//累计缴纳订单
        $arr = ['feeType' => 3, 'user_id' => $id, 'status' => 2];
        $cumulativeConsumptionOrders = ElectricPaymentOrder::getOrdersByWhere('*', $arr, 0);
        if ($cumulativeConsumptionOrders) {
            $cumulativeConsumption = array_sum(array_column($cumulativeConsumptionOrders, 'paymentMoney'));
        } else {
            $cumulativeConsumption = 0;
        }

        return array($cumulativeConsumptionOrders, $cumulativeConsumption);//累计费用
    }

    /**
     * 最后缴纳费用
     * @param array $user
     * @param  $plan
     * @param $paid_order_total
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author Sdd
     */
    public static function getNowBalance($user, $plan)
    {
//最后缴费记录
        $where = ['feeType' => 3, 'user_id' => $user['id'], 'status' => 2];
        $fields = 'id,months';
        $last_log = ElectricPaymentOrder::getOneOrderByWhere($where, $fields, 1);//最后缴费记录
        $one_price = bcmul($user['housing_area'], $plan['unit_price'], 2);//单月物业费
        $year_total = bcmul($one_price, 12, 2);//本年度需缴纳费用

        if (empty($last_log)) {//如果没有交过费
            if (isset($user['last_payment_time']) && $user['last_payment_time'] != '') {
                $last_month = date('m', $user['last_payment_time']);//最后缴费月份
            } else {
                $last_month = "无";//最后缴费月份
            }

        } else {
            $month_arr = explode(',', $last_log['months']);
            $last_month = $month_arr[count($month_arr) - 1];//最后缴费月份
        }

        return array($one_price, $year_total, $last_month);
    }

    /**
     * 物业费所属v字段
     * @param $user
     * @param $plan
     * @param $one_price
     * @return array
     */
    public function get_property_need($user, $plan, $one_price)
    {

        $order_db = ElectricPaymentOrder::where(['user_id' => $user['id'], 'feeType' => 3, 'status' => 2])->orderByDesc('id')->get();
        if ($order_db) {
            $order = $order_db->toArray();
        } else {
            $order = [];
        }
        $last_pay_time = $order[count($order) - 1]['paymentTime'];
        $last_payment_year = date('Y', strtotime($last_pay_time));//最终缴费年份
        $now_year = date('Y');//最终缴费年份
        $now_m = date('m');//最终缴费年份
        $paid_month = $this->getPaidMonth($order);
        [$billed_arr,$billed_month] = $this->getBilledArr($last_payment_year, $now_year, $now_m, $user, $plan, $paid_month, $one_price);//已支付月份
        //未出帐
        $unpaid_arr = $this->getUnpaidArr($now_m, $now_year, $one_price);
        $cha = array_values(array_diff($billed_month, $paid_month));//没交物业费月份
        $arrears = bcmul(count($cha), $one_price);//物业费欠费
        return array($arrears, $cha, $billed_arr, $paid_month, $unpaid_arr);
    }

    /**
     * 2021/3/20--15:49
     * @effect:
     * @param bool $now_m
     * @param bool $now_year
     * @param string $one_price
     * @return array
     * @author:苏冬冬
     * @QQ:1299273928
     * @method:getUnpaidArr
     */
    public function getUnpaidArr(bool $now_m, bool $now_year, string $one_price): array
    {
        $unpaid_arr = [];
        for ($x = $now_m + 1; $x <= 12; $x++) {

            $date = $now_year . '.' . str_pad($x, 2, 0, STR_PAD_LEFT);
            $unpaid_arr[] = [
                'month' => $date,
                'one_price' => $one_price,
                'pay_status' => 0,
            ];
        }
        return $unpaid_arr;
    }

    /**
     * 2021/3/20--16:16
     * @effect:获取已出帐月份
     * @author:苏冬冬
     * @QQ:1299273928
     * @method:getBilledArr
     * @param $last_payment_year
     * @param $now_year
     * @param $now_m
     * @param $user
     * @param $plan
     * @param array $paid_month
     * @param string $one_price
     * @return array[]
     */
    public function getBilledArr($last_payment_year,  $now_year,  $now_m, $user, $plan, array $paid_month, string $one_price): array
    {
        $billed_month = [];//需缴费月份
        $billed_arr = [];
        for ($i = $last_payment_year; $i <= $now_year; $i++) {
            if ($now_year == $i) {
                $number = $now_m;
            } else {
                $number = 12;
            }
            $one_price = bcmul($user['housing_area'], $plan['unit_price'], 2);//单月物业费
            for ($x = 1; $x <= $number; $x++) {
                $date = $i . '.' . str_pad($x, 2, 0, STR_PAD_LEFT);
                $billed_month [] = $date;
                if (in_array($date, $paid_month)) {
                    $pay_status = 1;
                } else {
                    $pay_status = 0;
                }
                $billed_arr[] = [
                    'month' => $date,
                    'one_price' => $one_price,
                    'pay_status' => $pay_status,
                ];
            }

        }
        return [$billed_arr, $billed_month];
    }

    /**
     * 2021/3/20--15:50
     * @effect:
     * @param array $order
     * @return array
     * @author:苏冬冬
     * @QQ:1299273928
     * @method:getPaidMonth
     */
    public function getPaidMonth(array $order): array
    {
        $paid_month = [];

        foreach ($order as $k => $v) {
            $month_arr = explode(",", $v['months']);
            $paid_month = array_merge($paid_month, $month_arr);
        }
        sort($paid_month);
        return $paid_month;
    }

}
